#include "Benzier.h"

Benzier::Benzier(vector<CCPoint>* _p, CCLayer* _layer)
{
	m_freeze = false;
	time =0;
	m_layer = _layer;
	p = _p;
	n = p->size() - 1;
	param = getParamBenzier(n);
	visibleSize = CCDirector::sharedDirector()->getVisibleSize();
	m_fish = CCSprite::create("fish1_01.png");

    // position the sprite on the center of the screen
    m_fish->setPosition(ccp(100,visibleSize.height/2));
	m_layer->addChild(m_fish);
}

Benzier::Benzier(void)
{
}
Benzier::~Benzier(void)
{
}
void Benzier::update(float t)
{
	if (m_freeze == false)
	{
	time +=0.1*t;
	old.setPoint(x,y);
    float px = 0, py =0;
	for (int i = 0; i <= n; i++) {
		float a = param[i];
		px += a * pow(1 - time, n - i) * pow(time, i) * p->at(i).x;
		py += a * pow(1 - time, n - i) * pow(time, i) * p->at(i).y;
	}
	x = px;
	y = py;
	cur.setPoint(x,y);

	float angle = atan2(-cur.y + old.y, cur.x - old.x) * 180 / M_PI;
	cur = ccpSub (cur, old);
	m_fish->setPosition(ccp(x,y));
	m_fish->setRotation(angle);
	}
}


vector<float> Benzier:: getParamBenzier(int n)
 {
	 int size = n+1;
	 vector<float> val (size);  
	 for (int i =0 ; i<= n;  i ++)
	 {
		 val[i] = binomial(n, i);
	 }
	 return val;
 }


float Benzier:: factorial(int n) {
		if (n <= 1) 
		{
			return 1;
		}
		return factorial(n - 1) * n;
}
 float Benzier::binomial(int n, int i) 
 {
		float _n = factorial(n);
		float _i = factorial(i);
		float n_i = factorial(n - i);
		return _n / (_i * n_i);
}